<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="酒店名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入酒店名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:hotel:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:hotel:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:hotel:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:hotel:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="hotelList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="酒店ID" align="center" prop="hotelId" />
      <el-table-column label="酒店名称" align="center" prop="name" />
      <el-table-column label="地址" align="center" prop="address" />
      <el-table-column label="联系电话" align="center" prop="phone" />
      <el-table-column label="营业执照" align="center">
        <template slot-scope="scope">
          <el-image :src="scope.row.businessLicense" style="width: 50px;"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="资格证书" align="center" >
        <template slot-scope="scope">
          <el-image :src="scope.row.certification" style="width: 50px;"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="入住时间" align="center" prop="inTime" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.inTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="离开时间" align="center" prop="outTime" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.outTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:hotel:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:hotel:remove']"
          >删除</el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['system:role:edit']">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="room" icon="el-icon-circle-check">房型管理</el-dropdown-item>
              <el-dropdown-item command="features" icon="el-icon-circle-check">特色管理</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改酒店对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="酒店名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入酒店名称" />
        </el-form-item>
        <el-form-item label="省份" prop="province">
          <el-select v-model="form.province" placeholder="选择城市" clearable>
            <el-option
              v-for="item in addressList"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="介绍" prop="introduce">
          <el-input v-model="form.introduce" placeholder="请输入介绍" type="textarea" :rows="3"/>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="星级" prop="starLevel">
          <div style="display: flex;justify-content: center;align-items: center">
            <el-rate v-model="form.starLevel"></el-rate>
          </div>
        </el-form-item>
        <el-form-item label="酒店图片" prop="image">
          <MyUpload ref="childUpload0" @callParent="transDownloadUrl0"></MyUpload>
        </el-form-item>
        <el-form-item label="营业执照" prop="businessLicense">
          <MyUpload ref="childUpload1" @callParent="transDownloadUrl1"></MyUpload>
        </el-form-item>
        <el-form-item label="资格证书" prop="certification">
          <MyUpload ref="childUpload2" @callParent="transDownloadUrl2"></MyUpload>
        </el-form-item>
        <el-form-item label="入住时间" prop="inTime">
          <el-time-picker
            v-model="form.inTime"
            placeholder="请选择入住时间">
          </el-time-picker>
        </el-form-item>
        <el-form-item label="离开时间" prop="outTime">
          <el-time-picker
            v-model="form.outTime"
            placeholder="请选择离开时间">
          </el-time-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="房型管理" :visible.sync="openRoom" width="600px" append-to-body>
      <el-table :data="hotelRoomList">
        <el-table-column label="房型" align="center" prop="name" />
        <el-table-column label="面积/㎡" align="center" prop="area">
          <template slot-scope="scope">
            <el-input v-model="scope.row.area"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="人数/间" align="center" prop="peopleNumber">
          <template slot-scope="scope">
            <el-input v-model="scope.row.peopleNumber"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="价格/晚" align="center" prop="price">
          <template slot-scope="scope">
            <el-input v-model="scope.row.price"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="总数量" align="center" prop="number">
          <template slot-scope="scope">
            <el-input v-model="scope.row.number"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="剩余数量" align="center" prop="remainNumber"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateHotelRoom" v-hasPermi="['system:room:edit']">保 存</el-button>
        <el-button @click="openRoom = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 特色管理弹窗 -->
    <el-dialog title="特色管理" :visible.sync="openFeatures" width="600px" append-to-body>
      <el-table 
        v-loading="featuresLoading" 
        :data="featuresList" 
        @selection-change="handleFeaturesSelectionChange"
        row-key="featuresId"
        ref="featuresTable"
      >
        <el-table-column 
          type="selection" 
          width="55" 
          align="center"
          :reserve-selection="true"
        />
        <el-table-column label="特色服务ID" align="center" prop="featuresId" />
        <el-table-column label="名称" align="center" prop="name" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleFeaturesAdd" v-hasPermi="['system:features:add']">保存</el-button>
        <el-button @click="openFeatures = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listHotel, getHotel, delHotel, addHotel, updateHotel } from "@/api/system/hotel"
import MyUpload from '@/components/upload';
import {listHotelRoom, updateBatchRoom} from "@/api/system/room";
import { listFeatures, getFeatures, delFeatures, addFeatures, updateFeatures } from "@/api/system/features"
import { addHotelFeatures } from "@/api/system/features"

export default {
  name: "Hotel",
  components: {
    MyUpload
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      openRoom: false,
      // 总条数
      total: 0,
      // 酒店表格数据
      hotelList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        address: null,
        introduce: null,
        phone: null,
        businessLicense: null,
        certification: null,
        inTime: null,
        outTime: null,
        province: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      imageUrl: null,
      addressList: [
        // 直辖市
        "北京", "上海", "天津", "重庆",
        // 广东省
        "广州", "深圳", "东莞", "佛山", "珠海", "中山", "惠州", "汕头", "江门", "湛江", "肇庆", "茂名",
        // 江苏省
        "南京", "苏州", "无锡", "常州", "南通", "徐州", "扬州", "盐城", "泰州", "镇江", "淮安", "连云港", "宿迁",
        // 浙江省
        "杭州", "宁波", "温州", "绍兴", "嘉兴", "金华", "台州", "湖州", "衢州", "丽水", "舟山",
        // 四川省
        "成都", "绵阳", "宜宾", "南充", "德阳", "泸州", "达州", "乐山", "眉山", "内江", "自贡", "攀枝花",
        // 湖北省
        "武汉", "宜昌", "襄阳", "荆州", "黄冈", "孝感", "十堰", "荆门", "鄂州", "咸宁", "随州",
        // 山东省
        "济南", "青岛", "烟台", "潍坊", "临沂", "淄博", "济宁", "泰安", "威海", "德州", "聊城", "菏泽", "日照", "枣庄",
        // 福建省
        "福州", "厦门", "泉州", "漳州", "莆田", "宁德", "三明", "南平", "龙岩",
        // 河南省
        "郑州", "洛阳", "南阳", "许昌", "周口", "新乡", "商丘", "驻马店", "信阳", "安阳", "开封", "平顶山",
        // 湖南省
        "长沙", "株洲", "湘潭", "衡阳", "岳阳", "常德", "邵阳", "郴州", "益阳", "永州", "怀化", "娄底", "张家界",
        // 其他省份重点城市
        // 河北省
        "石家庄", "保定", "唐山", "邯郸", "廊坊", "沧州", "邢台", "秦皇岛", "衡水", "张家口",
        // 陕西省
        "西安", "咸阳", "宝鸡", "渭南", "汉中", "榆林", "延安", "安康", "商洛",
        // 辽宁省
        "沈阳", "大连", "鞍山", "抚顺", "锦州", "营口", "盘锦", "丹东", "辽阳", "本溪",
        // 其他地区
        "合肥（安徽）", "芜湖（安徽）", "南昌（江西）", "赣州（江西）",
        "太原（山西）", "大同（山西）", "呼和浩特（内蒙古）", "包头（内蒙古）",
        "南宁（广西）", "柳州（广西）", "桂林（广西）", "海口（海南）", "三亚（海南）",
        "贵阳（贵州）", "遵义（贵州）", "昆明（云南）", "曲靖（云南）",
        "兰州（甘肃）", "天水（甘肃）", "银川（宁夏）", "西宁（青海）",
        "乌鲁木齐（新疆）", "克拉玛依（新疆）", "拉萨（西藏）",
        // 港澳台
        "香港", "澳门", "台北（台湾）", "高雄（台湾）", "台中（台湾）", "新北（台湾）"
      ],
      hotelRoomList: [],
      // 特色管理相关
      openFeatures: false,
      featuresLoading: false,
      featuresList: [],
      selectedFeatures: [], // 选中的特色列表
      currentHotelId: null, // 当前操作的酒店ID
    }
  },
  created() {
    this.getList()
  },
  methods: {
    updateHotelRoom() {
      updateBatchRoom(this.hotelRoomList).then(response => {
        this.$message.success("操作成功");
      })
    },
    handleCommand(command, row) {
      if (command === 'room') {
        this.handleRoom(row)
      } else if (command === 'features') {
        this.handleFeatures(row)
      }
    },
    handleRoom(row) {
      this.openRoom = true;
      listHotelRoom(row.hotelId).then(response => {
        this.hotelRoomList = response.data;
      })
    },
    transDownloadUrl0(url) {
      this.form.image = url;
    },
    transDownloadUrl1(url) {
      this.form.businessLicense = url;
    },
    transDownloadUrl2(url) {
      this.form.certification = url;
    },
    getList() {
      this.loading = true
      listHotel(this.queryParams).then(response => {
        this.hotelList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        hotelId: null,
        name: null,
        address: null,
        introduce: null,
        phone: null,
        image: null,
        businessLicense: null,
        certification: null,
        inTime: null,
        outTime: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.hotelId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加酒店"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const hotelId = row.hotelId || this.ids
      getHotel(hotelId).then(response => {
        this.form = response.data
        // 处理时间字符串转换为时间对象
        if (this.form.inTime) {
          const [hours, minutes] = this.form.inTime.split(':')
          this.form.inTime = new Date(2000, 0, 1, parseInt(hours), parseInt(minutes))
        }
        if (this.form.outTime) {
          const [hours, minutes] = this.form.outTime.split(':')
          this.form.outTime = new Date(2000, 0, 1, parseInt(hours), parseInt(minutes))
        }
        this.open = true
        this.title = "修改酒店"
        this.$nextTick(() => {
          this.$refs.childUpload1.setImgUrl(this.form.businessLicense);
        })
        this.$nextTick(() => {
          this.$refs.childUpload2.setImgUrl(this.form.certification);
        })
        this.$nextTick(() => {
          this.$refs.childUpload0.setImgUrl(this.form.image);
        })
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.inTime) {
            const inTime = new Date(this.form.inTime);
            this.form.inTime = `${inTime.getHours().toString().padStart(2, '0')}:${inTime.getMinutes().toString().padStart(2, '0')}`;
          }
          if (this.form.outTime) {
            const outTime = new Date(this.form.outTime);
            this.form.outTime = `${outTime.getHours().toString().padStart(2, '0')}:${outTime.getMinutes().toString().padStart(2, '0')}`;
          }
          
          if (this.form.hotelId != null) {
            updateHotel(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addHotel(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const hotelIds = row.hotelId || this.ids
      this.$modal.confirm('是否确认删除酒店编号为"' + hotelIds + '"的数据项？').then(function() {
        return delHotel(hotelIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/hotel/export', {
        ...this.queryParams
      }, `hotel_${new Date().getTime()}.xlsx`)
    },
    // 特色管理
    handleFeatures(row) {
      this.openFeatures = true
      this.currentHotelId = row.hotelId
      this.selectedFeatures = row.features || [] // 确保selectedFeatures始终是数组
      this.getFeaturesList()
    },
    // 获取特色列表
    getFeaturesList() {
      this.featuresLoading = true
      listFeatures({
        pageSize: 100
      }).then(response => {
        this.featuresList = response.rows
        this.featuresLoading = false
        // 在数据加载完成后，设置选中状态
        this.$nextTick(() => {
          if (this.selectedFeatures && this.selectedFeatures.length > 0) {
            this.selectedFeatures.forEach(featureId => {
              const row = this.featuresList.find(item => item.featuresId === featureId)
              if (row) {
                this.$refs.featuresTable.toggleRowSelection(row, true)
              }
            })
          } else {
            this.$refs.featuresTable.clearSelection()
          }
        })
      })
    },
    // 特色选择变化
    handleFeaturesSelectionChange(selection) {
      this.selectedFeatures = selection.map(item => item.featuresId)
    },
    // 保存特色关联
    handleFeaturesAdd() {
      if (!this.selectedFeatures.length) {
        this.$modal.msgError("请选择要关联的特色")
        return
      }
      addHotelFeatures({
        hotelId: this.currentHotelId,
        featuresIds: this.selectedFeatures
      }).then(response => {
        this.$modal.msgSuccess("保存成功")
        this.openFeatures = false
        this.getList()
      })
    },
  }
}
</script>
